package com.hopu.service.impl;

import com.hopu.context.BaseContext;
import com.hopu.entity.Interaction;
import com.hopu.entity.Video;
import com.hopu.entity.WorkCollectDTO;
import com.hopu.mapper.VideoMapper;
import com.hopu.mapper.interactionMapper;
import com.hopu.service.CollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CollectServiceImpl implements CollectService {

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private com.hopu.mapper.interactionMapper interactionMapper;

    /**
     * 收藏/取消收藏
     * @param workCollectDTO
     */
    @Transactional
    @Override
    public void toggleCollect(WorkCollectDTO workCollectDTO) {

        //获取当前用户id
        Integer userId = BaseContext.getCurrentId();

        //判断是否有记录,用户视频关系表
        Interaction interaction = interactionMapper.getByUserIdAndInteractionId(userId, workCollectDTO.getWorkId());

        //没记录
        if (interaction == null) {
            //封装数据
            Interaction inter = new Interaction();
            inter.setUserId(userId);
            inter.setWorkId(workCollectDTO.getWorkId());
            //设置收藏状态为1
            Short collectStatus = 1;
            inter.setCollectStatus(collectStatus);
            //插入数据
            interactionMapper.insert(inter);
            //收藏数加1
            videoMapper.incrementCollectCount(workCollectDTO);
        }else {
            //有记录,获取收藏状态
            Short currentStatus = interaction.getCollectStatus();
            if (currentStatus==null){
                currentStatus=Short.valueOf("0");
            }
            if (currentStatus == 1) {
                //已收藏,取消收藏
                Short toggleCollectStatus = 0;
                interaction.setCollectStatus(toggleCollectStatus);
                //更新收藏状态
                interactionMapper.updateCollectStatus(interaction);
                //收藏数减1
                videoMapper.decrementCollectCount(workCollectDTO);
            }else {
                //未收藏,重新收藏
                Short toggleCollectStatus = 1;
                interaction.setCollectStatus(toggleCollectStatus);
                //更新收藏状态
                interactionMapper.updateCollectStatus(interaction);
                //收藏数加1
                videoMapper.incrementCollectCount(workCollectDTO);
            }
        }
    }

    /**
     * 获取收藏数量
     * @param video
     * @return
     */
    @Override
    public Integer getCollectCount(Video video) {
        Integer workId = video.getWorkId();
        return videoMapper.getCollectCount(workId);
    }
}
